package com.yan.demo3;

import java.util.Random;
import java.util.concurrent.Semaphore;

/**
 * @author taoge
 * @Date 2024/8/9 10:36
 * @Description Semaphore 信号量
 */
public class Demo3 {
    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            Semaphore semaphore = new Semaphore(3);

            @Override
            public void run() {
                long start = System.currentTimeMillis();
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(Thread.currentThread().getName() + "进入了停车场");

                try {
                    Thread.sleep(new Random().nextInt(2001) + 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(Thread.currentThread().getName() + "离开了停车场");
                semaphore.release();
                long end = System.currentTimeMillis();
                System.out.println((end - start) / 1000);
            }
        };

        for (int i = 1; i <= 10; i++) {
            new Thread(runnable , "车辆" + i).start();
        }


    }
}
